package com.boarsoft.boar.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.boarsoft.boar.app.AppBiz;
import com.boarsoft.boar.app.AppInstBiz;
import com.boarsoft.boar.entity.AppInfo;
import com.boarsoft.boar.entity.AppInst;
import com.boarsoft.soagov.bean.AppInstReg;
import com.boarsoft.soagov.registry.ServiceRegistry;

@Component("serviceRegistry")
public class ServiceRegistryImpl implements ServiceRegistry {

	@Autowired
	protected AppInstBiz appInstBiz;
	@Autowired
	protected AppBiz appBiz;

	@Override
	public List<AppInstReg> list(String ip) {
		List<AppInst> oLt = appInstBiz.list(ip);
		List<AppInstReg> rLt = new ArrayList<>();
		for (AppInst o : oLt) {
			rLt.add(this.toAppInstReg(o));
		}
		return rLt;
	}

	@Override
	public AppInstReg find(String ip, int port) {
		AppInst o = appInstBiz.find(ip, port);
		if (o == null) {
			throw new IllegalStateException(//
					new StringBuilder("Can not find app inst with ")//
							.append(ip).append(":").append(port).toString());
		}
		return this.toAppInstReg(o);
	}

	protected AppInstReg toAppInstReg(AppInst o) {
		AppInstReg r = new AppInstReg();
		r.setAddr(o.getAddr());
		r.setPath(o.getDeployPath());
		AppInfo a = o.getApp();
		r.setHandler(a.getHandler());
		r.setAppCode(a.getCode());
		return r;
	}

	@Override
	public List<String> getProviders(String env, String sk) {
		String[] a = sk.split("/");
		String group = a[0];
		String appId = a[1];
		List<AppInst> oLt = appInstBiz.list(env, appId, group, null);
		List<String> rLt = new ArrayList<>();
		for (AppInst o : oLt) {
			rLt.add(o.getAddr());
		}
		return rLt;
	}

	@Override
	public String getHandler(String appId) {
		AppInfo a = appBiz.get(appId);
		return a == null ? null : a.getHandler();
	}
}